package server;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLSocket;

import utils.Hashes;
import common.Lists;

public class ClientKicker implements Runnable
{

	private int ServerID;
	public ClientKicker (int sID)
	{
		this.ServerID = sID;
	}
	@Override
	public void run() 
	{
		while(true)
		{
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int ServerGroupID = Hashes.getGroupIdFromServerId(ServerID);
		
		Iterator<Entry<Integer, ServerSendMsg>> it = RelayMessages.getInstance().getServerThreads().entrySet().iterator();
		while(it.hasNext())
		{
			Map.Entry pairs = it.next();
			
			List<Integer> ClientGroup = Hashes.getGroupIdListFromClientId(Integer.parseInt((String) pairs.getKey()));
			
			Object[] CGroup = ClientGroup.toArray();
			for(int i = 0; i < CGroup.length; i++)
			{			
				if((Integer)CGroup[i] == ServerGroupID && i == 0)
				{
					break;
				}
				
				if(Lists.getInstance().getLiveServerGroup((Integer)CGroup[i]).size() != 0 && i > 0)
				{
					try {
						((SSLSocket)pairs.getValue()).close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					RelayMessages.getInstance().getServerThreads().remove(pairs.getKey());
					
				}
			}
		}
		}
				
	}

}
